<template>
	<view>
		<!-- <image src="../../static/bg.jpg" mode=""></image> -->
		<canvas type="2d" class="canvasPoster" id="canvasPoster" :style="{width: width + 'px', height: height + 'px' }"></canvas>
		<canvas type="2d" id="waterMark" :style="{width:settings.width + 'px' , height : settings.height + 'px', position: 'fixed', 'top': '-2000rpx'}"></canvas>
		<!-- <canvas class="canvasPoster" canvas-id="canvasPoster" :style="{width: width + 'px', height: height + 'px' }"></canvas> -->
	</view>
</template>

<script>
	import { base64ToPath } from 'image-tools'
	import { getCanvasContext, CustomCanvas } from '../../utils/canvas.utils'
	import makeWatermark from '../../utils/mark'
	import { promisify } from '../../utils/promisify'
	import QR from "../../utils/wxqrcode"; // 二维码生成器

	export default {
		data() {
			return {
				width: 0,
				height: 0,
				sysInfo: {},
				imagesUrl: ['../../static/bg.jpg'],
				settings: {
					'id': 'waterMark',                  /* canvas id */
					'content': '寒暄查店',            /* 水印内容 */
					'width': 100,                       /* 图片/canvas 宽度 */
					'height': 100,                      /* 图片/canvas 高度 */ 
					'rotate': 60,                      /* 水印文案旋转角度*/ 
					'left':20,                          /* 水印文案相对图片水平偏移量 */
					'top':20,                           /* 水印文案相对图片垂直偏移量 */
					'fontSize': '15px',                 /* 水印文字大小 */
					'fontFamily': 'Microsoft JhengHei', /* 水印文字样式 */
					'bg': '#fff',                       /* 图片背景颜色 */ 
					'color': '#ccc',                    /* 水印文字颜色 */
					'fontWeight': 'normal',             /* 水印文字宽度 */
				}
			};
		},

		async onReady() {
			
			uni.showToast({
				icon:'loading',
				mask:true,
				duration:10000,
				title: '海报绘制中',
			});
			await this.resizeCanvas()
			const waterMarkUrl = await this.getWaterMask()
			// console.log(waterMarkUrl)
			console.log(this.getQrCode())
			const images = await Promise.all(this.imagesUrl.map(url => this.getImageInfo(url)))
			const imgLoadSucc = images.every(img => img.errMsg === 'getImageInfo:ok')
			const {width, height} = this;
			const instance = new CustomCanvas({id: '#canvasPoster', width, height})
			// const ctx = await getCanvasContext('#canvasPoster', this.width, this.height)
			const ctx = await instance.getContext();
			// console.log(instance)
			// console.log('context', ctx)
			if(imgLoadSucc) {
				ctx.fillStyle = '#fff'; // 默认白色
				ctx.fillRect(0, 0, this.width, this.height) // fillRect(x,y,宽度，高度)
				await instance.drawWaterMarker(waterMarkUrl)
				const {height} = await instance.drawImage(this.imagesUrl[0], 0, 0, this.width, this.height)
				// ctx.drawImage(this.imagesUrl[0], 0, 0, this.width, this.height)
				const text = '这是一段生成海报的测试文字这是一段生成海报的测试文字'
				await instance.drawText(text, 20, height + 20, 300)
				uni.canvasToTempFilePath({
					canvas: instance.node,
					quality: 1,
					x: 0,
					y: 0,
					width: this.width,
					height: this.height,
					success: (result) => {
						console.log(result)
						uni.hideToast()
						uni.saveImageToPhotosAlbum({
							filePath: result.tempFilePath,
							success(result) {
								console.log(result)
							}
						})
					}
				})
			}
		},
		// async onReady() {
		// 	uni.showToast({
		// 		icon:'loading',
		// 		mask:true,
		// 		duration:10000,
		// 		title: '海报绘制中',
		// 	});
		// 	this.sysInfo = await this.getSystemInfo()
		// 	// console.log(this.sysInfo)
		// 	const images = await Promise.all(this.imagesUrl.map(url => this.getImageInfo(url)))
		// 	// console.log(images)
		// 	this.width = this.sysInfo.screenWidth
		// 	this.height = this.sysInfo.screenHeight
		// 	const imgLoadSucc = images.every(img => img.errMsg === 'getImageInfo:ok')
		// 	if(imgLoadSucc) {
		// 		await this.$nextTick() // ! 为啥要delay
		// 		// await this.delay() // ! 为啥要delay
		// 		const ctx = uni.createCanvasContext('canvasPoster', this)
		// 		// 填充背景色，白色
		// 		ctx.setFillStyle('#fff'); // 默认白色
		// 		ctx.fillRect(0, 0, this.width, this.height) // fillRect(x,y,宽度，高度)
		// 		ctx.drawImage(this.imagesUrl[0], 0, 0, this.width, this.height)
		// 		// 主题内容留白
		// 		const content = 300
		// 		ctx.fillRect(0, this.height - 300, this.width, 300)
				
		// 		ctx.setFontSize(20)
		// 		ctx.setFillStyle('#333')
		// 		const text = '这是一段生成海报的测试文字这是一段生成海报的测试文字'
		// 		const textWidth = Math.floor(this.width * .6)
		// 		const texts = this.getTextsByTextWidth(textWidth, text, ctx);
		// 		console.log(texts)
		// 		texts.forEach((text, index) => {
		// 			const x = 10;
		// 			const y = this.height - 270 + (index* 30)
		// 			ctx.fillText(text, x, y)
		// 		})
				
		// 		ctx.draw(true, (result) => {
		// 			console.log(result)
		// 			uni.showToast({
		// 				title: '绘制完成',
		// 				icon: 'success',
		// 				mask: true
		// 			})
		// 			uni.canvasToTempFilePath({
		// 				canvasId: 'canvasPoster',
		// 				quality: 1,
		// 				x: 0,
		// 				y: 0,
		// 				width: this.width,
		// 				height: this.height,
		// 				success: (result) => {
		// 					console.log(result)
		// 					uni.saveImageToPhotosAlbum({
		// 						filePath: result.tempFilePath,
		// 						success(result) {
		// 							console.log(result)
		// 						}
		// 					})
		// 				}
		// 			})
		// 		})
				
				
		// 	}
		// },
		methods: {
			async getQrCode() {
				const qrCode = QR.createQrCodeImg( //生成二维码
					`https://anydoor.emdlz.com.cn/api-pointsmall/api/wxminiAuth/security/5007/c/`, {
						size: parseInt(300), //二维码大小
						typeNumber: 7,
					}
				)
				console.log(qrCode)
				const path = await base64ToPath(qrCode)
				console.log(path)
			},
			getWaterMask() {
				return new Promise(resolve => {
					/* 创建一个  makeWatermark 对象 */
					const marker = makeWatermark(this.settings)
					/* 调用make，生成图片 */
					marker.make((url)=>{
						/* url 为临时路径  */
						// console.log(url)
						resolve(url)
					})
				})
				
			},
			async resizeCanvas() {
				this.sysInfo = await this.getSystemInfo()
				console.log('sysInfo', this.sysInfo)
				this.width = this.sysInfo.screenWidth
				this.height = this.sysInfo.screenHeight
			},
			// 根据文本宽度将要书写文字分行输出
			getTextsByTextWidth(lineWidth, text, ctx) {
				return text.split('').reduce((prev, next) => {
					if(prev.length > 0) {
						const {width: lastTextWidth} = ctx.measureText(prev[prev.length - 1].join(''))
						const {width: singleTextWidth} = ctx.measureText(next)
						if((lastTextWidth + singleTextWidth) <= lineWidth) {
							prev[prev.length - 1].push(next)
						} else {
							prev.push([next])
						}
						
					} else {
						prev.push([next])
					}
					return prev
				}, []).map(item => item.join(""))
			},
			// 获取图片信息
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
					});
				})
			},
			
			// 获取设备信息
			getSystemInfo(){
				return promisify(uni.getSystemInfo)()
				// return new Promise((req, rej) => {
				// 	uni.getSystemInfo({
				// 	    success: function (res) {
				// 	        req(res)
				// 	    }
				// 	});
				// })
			},
			delay(timer = 1000) {
				return new Promise(resolve => {
					setTimeout(() => {
						resolve()
					}, timer)
				})
			}
		},
	}
</script>

<style lang="scss">
.canvasPoster {
	position: fixed;
	top: 0;
	left: 0;
}
</style>
